import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { getToken, removeToken } from './auth' // 假设存在token管理工具

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL, // 从环境变量获取基础地址
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 加载实例
let loadingInstance = null
// 当前请求数量
let requestCount = 0

// 显示加载
const showLoading = () => {
  if (requestCount === 0) {
    loadingInstance = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.1)'
    })
  }
  requestCount++
}

// 隐藏加载
const hideLoading = () => {
  if (requestCount <= 0) return
  requestCount--
  if (requestCount === 0) {
    loadingInstance?.close()
  }
}

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 显示加载动画（可以通过配置关闭）
    if (config.showLoading !== false) {
      showLoading()
    }
    // 添加token
    const token =  localStorage.getItem('token');
    const userId = localStorage.getItem('userId');
    if (token) {
      config.headers.token = token;
      config.headers['userId'] = userId;
    }
    
    // 设置取消请求
    if (config.cancelToken === undefined) {
      const controller = new AbortController()
      config.signal = controller.signal
      config.cancel = () => controller.abort()
    }
    
    return config
  },
  (error) => {
    hideLoading()
    ElMessage.error('请求配置错误: ' + error.message)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    hideLoading()
    
    const res = response.data
    
    // 根据实际后端约定的状态码处理
    if (res.code !== 200) {
      // 未登录或token过期
      if (res.code === 401) {
        removeToken('token')
        removeToken('userId')
        ElMessage.error('登录已过期，请重新登录');
        // 跳转到登录页
        setTimeout(() => {
          window.location.href = '/'
        }, 1000)
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    }
    
    return res
  },
  (error) => {
    hideLoading()
    
    // 处理取消请求
    if (axios.isCancel(error)) {
      console.log('请求已取消:', error.message)
      return Promise.reject(new Error('请求已取消'))
    }
    
    // 处理网络错误
    let errorMsg = '网络错误，请稍后重试'
    if (error.response) {
      switch (error.response.status) {
        case 404:
          errorMsg = '请求地址不存在'
          break
        case 500:
          errorMsg = '服务器内部错误'
          break
        case 403:
          errorMsg = '没有权限访问'
          break
        default:
          errorMsg = `请求错误 (${error.response.status})`
      }
    }
    
    ElMessage.error(errorMsg)
    return Promise.reject(error)
  }
)

// 封装请求方法
const request = {
  get(url, params = {}, config = {}) {
    return service.get(url, { params, ...config })
  },
  
  post(url, data = {}, config = {}) {
    return service.post(url, data, config)
  },
  
  put(url, data = {}, config = {}) {
    return service.put(url, data, config)
  },
  
  delete(url, params = {}, config = {}) {
    return service.delete(url, { params, ...config })
  },
  
  // 上传文件
  upload(url, file, onProgress, config = {}) {
    const formData = new FormData()
    formData.append('file', file)
    
    return service.post(url, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      onUploadProgress: (progressEvent) => {
        const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100)
        onProgress && onProgress(percent)
      },
      ...config
    })
  }
}

export default request